import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;

public class FindForm extends Form implements CommandListener 
{
	private static final Command CMD_OK = new Command("OK", Command.OK, 1);
    private static final Command CMD_CANCEL = new Command("Cancel", Command.CANCEL, 1);
    private Table parent;
    private Display display;
    private TextField findTextBox;
    private Spacer spacer;
    private List foundList;
	private String[] results = new String[]{"No match found"};
	private char[] searchChars;

    public FindForm(Table parent, Display display) 
	{
		super("Enter the value to find");

		findTextBox = new TextField("Find",null,50,TextField.ANY);
		spacer = new Spacer(0,50);

        this.parent = parent;
        this.display = display;
        addCommand(CMD_OK);
        addCommand(CMD_CANCEL);

		append(spacer);
		append(findTextBox);

        setCommandListener(this);
    }

    public void commandAction(Command c, Displayable d) 
	{
		if (c == CMD_OK) 
		{	

			foundList = new List("Search result", Choice.IMPLICIT, results, null);
			String search = findTextBox.getString();
			searchChars = new char[10];
			search.getChars(0,search.length(),searchChars,0);

			int k=0;
			for(int i=0; i< 925; i++)
			{
				for(int j=0; j<125; j++)
				{
					if(parent.data[i][j].equals(""))
					{
						continue;
					}

					boolean exists = CheckValueExists(i,j,search.length());
					if(exists == true)
					{
						String result = ""+i+","+j+"-"+parent.data[i][j];
						if(k == 0)
						{
							foundList.append(result,null);
							foundList.delete(k);
						}
						else
							foundList.append(result,null);

						k++;
					}
				}
			}

		        foundList.setCommandListener(this);
      	  	  display.setCurrent(foundList);
		}
		else if (c == CMD_CANCEL) 
		{
			display.setCurrentItem(parent);
        }
		if(d.equals(foundList))
		{
			int index = ((List)d).getSelectedIndex();
			String selectedOption = ((List)d).getString(index);
			parent.findText(selectedOption);
	            display.setCurrentItem(parent);		
		}
	}

	private boolean CheckValueExists(int ii,int jj, int length)
	{
		int startIndex = 0;
		int previousIndex = 0;
		while((startIndex = parent.data[ii][jj].indexOf(searchChars[0],previousIndex)) != -1)
		{
			if(length > parent.data[ii][jj].length() - startIndex )
			{
				return false;
			}

			for(int i=0;i< length; i++)
			{
				if(searchChars[i] != parent.data[ii][jj].charAt(startIndex + i))
				{	
					break ;				
				}
				if(i == length - 1)
				{
					return true;
				}
			}
			previousIndex = startIndex + 1;
		}

		return false;
	}
}
